Leetcode JS 2627. Debounce


Posted by Lucy on 2023-06-05

其實應該先寫Debounce再寫Throttle,不過因為Throttle花比較久時間所以先寫。

var debounce = function(fn, t=500) {
    let timer=null;
    return function(...args) {
        clearTimeout(timer)
        timer=setTimeout(()=>{fn.apply(this,args)},t)
    }
}

上面這段算是最簡單的debounce,可以根據需求再做擴展,比較有名的debounce大概就lodash的debounce吧,剛好最近有遇到一個覺得用Debounce很適合的需求。
需求為當網頁閒置一段時間後,就要自動登出,閒置的定義為滑鼠沒有移動來做偵測

        let delayTime = 分 * 60 * 1000;
        const timeout = debounce(() => {
            //...logout處理
        }, delayTime);
        document.body.addEventListener('mousemove', timeoutFn);
        //記得登出前要把事件取消掉

因為滑鼠事件會一直移動,感覺再加個Throttle做限制好像也行,目前簡易登出偵測大概就這樣,有想到再來補充。


#Leetcode







Related Posts

我要成為前端工程師的學習筆記:HTML & CSS 篇 -  CSS 介紹  Day2

我要成為前端工程師的學習筆記:HTML & CSS 篇 - CSS 介紹 Day2

[ 筆記 ] React 01 - Component、JSX 語法、事件機制

[ 筆記 ] React 01 - Component、JSX 語法、事件機制

[Day 01] 單例模式及簡單工廠設計模式

[Day 01] 單例模式及簡單工廠設計模式


Comments